package com.qingke.stockdata.service;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.qingke.stockdata.exception.InvalidStockCodeException;
import com.qingke.stockdata.mappers.StockDao;
import com.qingke.stockdata.model.Stock;
import com.qingke.stockdata.model.StockData;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:springConfig.xml" })
public class StockServiceTest {

	@Autowired
	private DataCrawler dataCrawler;

	@Autowired
	private StockDao stockDao;

	@Test
	public void testAddStock() {
		String code = "sh601006";
		Stock stock = null;
		try {
			// 获取stock基本信息
			stock = dataCrawler.getStock(code);
			// 获取历史数据并保存
			List<StockData> stockDatas = dataCrawler.getStockHist(code);
			stockDao.addStockDetail(stockDatas);
			int minIndex = 0;// 记录最小low值的索引
			int maxIndex = 0;// 记录最大high值得索引
			for (int i= 0;i < stockDatas.size();i++) {
				StockData sd = stockDatas.get(i);
				// 计算历史最低和最高字段，返回页面、插入数据库
				if(sd.getHigh()> stockDatas.get(maxIndex).getHigh()){
					maxIndex = i;
				}
				if (sd.getLow() < stockDatas.get(minIndex).getLow()) {
					minIndex = i;
				}
			}
			stock.setHistoryHigh(stockDatas.get(maxIndex).getHigh());
			stock.setHisotryLow(stockDatas.get(minIndex).getLow());
			stockDao.addStock(stock);
		} catch (InvalidStockCodeException e) {
			e.printStackTrace();
		}
	}

}
